package com.group11.invite.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group11.common.pojo.ResponseResult;
import com.group11.common.pojo.Resume;
import com.group11.invite.domain.Invite;
import com.group11.invite.domain.JobSend;
import com.group11.invite.mapper.JobSendMapper;
import com.group11.invite.service.JobSendService;
import com.group11.invite.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class JobSendServiceImpl extends ServiceImpl<JobSendMapper, JobSend> implements JobSendService {

    @Autowired
    private JobSendMapper jobSendMapper;

    @Autowired
    private InviteServiceImpl inviteService;
    @Autowired
    private ResumeService resumeService;

    @Override
    public boolean addJobSend(JobSend jobSend, int id) {
        jobSend.setSendTime(LocalDateTime.now().toString());
        jobSend.setViewed("0");
        jobSend.setStatus("0");
        ResponseResult<List<Resume>> listResponseResult = resumeService.listByUserId(id);
        if (listResponseResult.getCode() != 200 || listResponseResult.getData() == null) {
            throw new RuntimeException("用户无简历");
        }

        List<Resume> resumes = listResponseResult.getData();
        for (Resume resume : resumes) {
            if (resume.getDef() == '1') {
                jobSend.setResumeId(resume.getId());
                break;
            }
        }

        if (jobSend.getResumeId() == 0) {
            throw new RuntimeException("无默认简历");
        }

        QueryWrapper<JobSend> jobSendQueryWrapper = new QueryWrapper<>();
        jobSendQueryWrapper
                .eq("job_id", jobSend.getJobId())
                .eq("resume_id", jobSend.getResumeId());
        JobSend jobSend1 = jobSendMapper.selectOne(jobSendQueryWrapper);
        if (jobSend1 != null) {
            throw  new RuntimeException("请勿重复投递");
        }

        int rows = jobSendMapper.insert(jobSend);
        return rows > 0;
    }

    @Override
    public List<JobSend> userSend(int id) {
        List<Integer> inviteByUserId = inviteService.getUserResumeIds(id);
        QueryWrapper<JobSend> jobSendQueryWrapper = new QueryWrapper<>();
        jobSendQueryWrapper.in("resume_Id", inviteByUserId);
        List<JobSend> jobSends = jobSendMapper.selectList(jobSendQueryWrapper);
        return jobSends;
    }

    @Override
    public boolean viewJobSend(int id) {
        UpdateWrapper<JobSend> jobSendUpdateWrapper = new UpdateWrapper<>();
        jobSendUpdateWrapper.eq("id", id).set("viewed", "1");
        int rows = jobSendMapper.update(jobSendUpdateWrapper);
        return rows > 0;
    }
}
